//
//  QGRecentChatController.m
//  qeegooChat
//
//  Created by heew on 16/1/7.
//  Copyright © 2016年 com.autozi. All rights reserved.
//

#import "QGRecentChatController.h"
#import "QGRecentChatCell.h"
#import "QGRecentChatModel.h"
//#import "QGChatFriendController.h"
//#import "QGChatGroupController.h"
//#import "QGRecentChatManager.h"
#import "QGRecentChatTitleView.h"
#import "QGChatFriendTalkModel.h"
#import "QGMessageExtendGroupModel.h"
#import "EaseConvertToCommonEmoticonsHelper.h"
//#import "GJGCChatFriendViewController.h"
//#import "GJGCChatGroupViewController.h"
//#import "GJGCRecentChatDataManager.h"

@interface QGRecentChatController () <UITableViewDelegate,UITableViewDataSource,EMChatManagerDelegate>

@property (strong, nonatomic) NSMutableArray *recentChats; /**最近聊天 */
@property (nonatomic,strong)UITableView *listTable;
@property (nonatomic,strong)QGRecentChatTitleView *titleView;
@property (nonatomic,strong)dispatch_queue_t recentChatDataManagerQueue;
@end

@implementation QGRecentChatController
- (NSMutableArray *)recentChats {
    if (_recentChats == nil) {
        _recentChats = [NSMutableArray array];
    }
    return _recentChats;
}
- (dispatch_queue_t)recentChatDataManagerQueue {
    if (_recentChatDataManagerQueue == nil) {
        _recentChatDataManagerQueue = dispatch_queue_create("QG_recent_chat_queue", DISPATCH_QUEUE_SERIAL);
    }
    return _recentChatDataManagerQueue;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleView = [[QGRecentChatTitleView alloc]init];
    self.navigationItem.titleView = self.titleView;
    GJGCRecentChatConnectState result = [[EaseMob sharedInstance].chatManager isConnected]? GJGCRecentChatConnectStateSuccess:GJGCRecentChatConnectStateFaild;
    self.titleView.connectState = result;
    
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:self.recentChatDataManagerQueue];
    [[EaseMob sharedInstance].chatManager loadAllConversationsFromDatabaseWithAppend2Chat:YES];
    [self didUnreadMessagesCountChanged];
    self.listTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - self.tabBarController.tabBar.viewHeight - self.contentOriginY) style:UITableViewStylePlain];
    self.listTable.delegate = self;
    self.listTable.dataSource = self;
    self.listTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.listTable];
    
}

#pragma mark - tableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.recentChats.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    QGRecentChatCell *recentCell = [QGRecentChatCell cellWithTableView:tableView];
    QGRecentChatModel *chatModel = self.recentChats[indexPath.row];
    [recentCell setContentModel:chatModel];
    
    return recentCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    return [self.dataManager contentHeightAtIndexPath:indexPath];
    return 75;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
//    QGRecentChatModel *contenModel = [ contentModelAtIndexPath:indexPath];
//    
//    if (contenModel.isGroupChat) {
//        
//        QGChatFriendTalkModel *talk = [[QGChatFriendTalkModel alloc]init];
//        talk.talkType = GJGCChatFriendTalkTypeGroup;
//        talk.toId = contenModel.toId;
//        talk.toUserName = contenModel.name.string;
//        talk.conversation = contenModel.conversation;
//        talk.groupInfo = contenModel.groupInfo;
//        
//        QGChatGroupController *groupChat = [[QGChatGroupController alloc] initWithTalkInfo:talk];
//        
//        [self.navigationController pushViewController:groupChat animated:YES];
//        
//        return;
//    }
    
//    QGChatFriendTalkModel *talk = [[QGChatFriendTalkModel alloc]init];
//    talk.talkType = GJGCChatFriendTalkTypePrivate;
//    talk.toId = contenModel.toId;
//    talk.toUserName = contenModel.name.string;
//    talk.conversation = contenModel.conversation;
//    
//    QGChatFriendController *privateChat = [[QGChatFriendController alloc] initWithTalkInfo:talk];
//    [self.navigationController pushViewController:privateChat animated:YES];
    
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
//    switch (editingStyle) {
//        case UITableViewCellEditingStyleDelete:
//        {
//            [self.dataManager deleteConversationAtIndexPath:indexPath];
//        }
//            break;
//            
//        default:
//            break;
//    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

#pragma mark - dispatch缓冲刷新会话列表
- (void)conversationListUpdate
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.view.window != nil) {
            [self.listTable reloadData];
        }
    });
}
#pragma mark - easeMobChatManager代理
- (void)didUnreadMessagesCountChanged
{
    NSArray *conversations = [[EaseMob sharedInstance].chatManager conversations];
    if (self.recentChats.count == 0 && conversations.count == 0) {
        return;
    }
    [self updateConversationList:conversations];
}

- (void)updateConversationList:(NSArray *)conversationList
{
    if (conversationList.count == 0) {
        return;
    }
    
    //重新载入一次会话列表
    if (self.recentChats.count > 0) {
        [self.recentChats removeAllObjects];
    }
    
    //按最后一条消息排序
    NSArray *sortConversationList = [conversationList sortedArrayUsingComparator:^NSComparisonResult(EMConversation *obj1, EMConversation *obj2) {
        
        NSComparisonResult result = obj1.latestMessage.timestamp > obj2.latestMessage.timestamp? NSOrderedAscending:NSOrderedDescending;
        
        return result;
        
    }];
    
    for (EMConversation *conversation in sortConversationList) {
        
        QGRecentChatModel *chatModel = [[QGRecentChatModel alloc]init];
        chatModel.toId = conversation.chatter;
        
        // 群聊
        if (conversation.conversationType == eConversationTypeGroupChat) {
            NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
            chatModel.headUrl = @"http://image.baidu.com/search/detail?ct=503316480&z=0&tn=baiduimagedetail&ipn=d&cl=2&cm=1&sc=0&lm=-1&ie=gbk&pn=0&rn=1&di=148491743290&ln=30&word=%B1%A6%C2%ED%D6%AE%C5%B51e%28%B5%E7%B6%AF%29&os=27216672,2189580673&cs=2174725735,2988436776&objurl=http%3A%2F%2Fupload.news.cecb2b.com%2F2014%2F0609%2F1402306537637.jpg&bdtype=0&simid=4159660666,467649274&fr=ala&ori_query=%E5%AE%9D%E9%A9%AC%E4%B9%8B%E8%AF%BA1e%28%E7%94%B5%E5%8A%A8%29&ala=0&alatpl=sp&pos=1";
            for (EMGroup *group in groupArray) {
                if ([group.groupId isEqualToString:conversation.chatter]) {
                    chatModel.name = group.groupSubject;
                }
            }
            chatModel.isGroupChat = YES;
            chatModel.unReadCount = conversation.unreadMessagesCount;
            chatModel.content = [self displayContentFromMessageBody:conversation.latestMessage];
            chatModel.time = [self displayTimeFromMessageBody:conversation.latestMessage];
        }
        // 单聊
        if (conversation.conversationType == eConversationTypeChat) {
            
            //对方的最近一条消息
            EMMessage *lastMessage = conversation.latestMessageFromOthers;
            
            if (lastMessage) {
                
                chatModel.name = lastMessage.to;
            }else{
                
                chatModel.name = conversation.chatter;
                chatModel.headUrl = @"";
            }
            
            chatModel.unReadCount = conversation.unreadMessagesCount;
            chatModel.isGroupChat = NO;
            
            chatModel.content = [self displayContentFromMessageBody:conversation.latestMessage];
            chatModel.time = [self displayTimeFromMessageBody:conversation.latestMessage];
        }
        chatModel.conversation = conversation;
        [self.recentChats addObject:chatModel];
    }
}
- (NSString *)displayTimeFromMessageBody:(EMMessage *)lastestMessage {
    double timeInterval = lastestMessage.timestamp;
    if (timeInterval > 140000000000) {
        timeInterval = timeInterval / 1000;
    }
    NSDate *ret = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    return  ret.description;
}

- (NSString *)displayContentFromMessageBody:(EMMessage *)lastestMessage {
    NSString *latestMessageTitle = @"";
    if (lastestMessage) {
        id <IEMMessageBody> messageBody = lastestMessage.messageBodies.lastObject;
        switch (messageBody.messageBodyType) {
            case eMessageBodyType_Image:{
                latestMessageTitle = NSLocalizedString(@"message.image1", @"[image]");
            }break;
            case eMessageBodyType_Text:{
                // 表情映射。
                NSString *didReceiveText = [EaseConvertToCommonEmoticonsHelper
                                            convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
                latestMessageTitle = didReceiveText;
            } break;
            case eMessageBodyType_Voice:{
                latestMessageTitle = NSLocalizedString(@"message.voice1", @"[voice]");
            } break;
            case eMessageBodyType_Location: {
                latestMessageTitle = NSLocalizedString(@"message.location1", @"[location]");
            } break;
            case eMessageBodyType_Video: {
                latestMessageTitle = NSLocalizedString(@"message.video1", @"[video]");
            } break;
            case eMessageBodyType_File: {
                latestMessageTitle = NSLocalizedString(@"message.file1", @"[file]");
            } break;
            default: {
            } break;
        }
    }
    return latestMessageTitle;
}
@end
